<?php

namespace app\store\controller;
use think\Request;
use think\Validate;
use think\Db;

class User extends ApiCommon
{
	
	public function _initialize()
    {
    	$this->nocheckArr = ['XcxGetOpenid','Login','userinfo','login','LoginHistory','loginhistory','xcxgetopenid','getuserinfo'];
        parent::_initialize();
    }
	
	//获取用户信息
	public function userinfo(){
		$uid = input('uid/d',0);
		$uinfo = get_user_info($uid);
		if($uinfo == null || count($uinfo)<=0){
			$this->returnMsg('400','用户信息错误');
		}
		
		$sinfo = get_store_info($uinfo['storeid']);
		$uinfo['storename'] = $sinfo['name']; 
		
		$infos = Db::query("select ml_game_reward.*,ml_game_reward.id as awardid,ml_goods.id,gname,icon,message from ml_game_reward,ml_goods 
		where ml_goods.id = goodsid and userid = $uid and ml_game_reward.state = 1");
		
		$this->returnMsg('ok','',['uinfo'=>$uinfo,'award'=>$infos]);
	}
	
	public function XcxGetOpenidtest(){
		
		include_once  "plugins/encrypted/wxBizDataCrypt.php";
		$codes = '\\wxBizDataCrypt';
		
		$code = input('code');	
		$storeid = input('storeid/d',0);		
		$storeinfo  = Db::name('store')->where(['store_id'=>$storeid])->select();
		if(count($storeinfo)<=0){
			$this->returnMsg('-1','获取店铺信息失败');
		}
		
		$secret = $storeinfo[0]['appsecret'];
		$appid = $storeinfo[0]['appid'];
		
		
		
		$GetOpenidUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$backdb = vget($GetOpenidUrl);
		
		if(!isset($backdb['openid'])){
			$this->returnMsg('-1','获取微信openid失败',['arr'=>$backdb]);
		}
		
		//$this->returnMsg('ok','登录成功',$backdb);
		$encryptedData = input('encryptedData');
		$iv = input('iv');
		$pc = new $codes($appid,$backdb['session_key']);
		$errCode = $pc->decryptData($encryptedData, $iv, $data );
		
		if ($errCode != 0) {
		    //$this->returnMsg('ok','登录成功',$data);
			$this->returnMsg('ok','登录失败',$errCode);
		}
		
		$data = json_decode($data,true);
		
		//$this->returnMsg('ok','登录失败ss',$data);
		$openid = $data['openId'];
		$userinfo = input('userInfo/a');		
		$userinfo['openid'] = $openid;
		$userinfo['headimgurl'] = $userinfo['avatarUrl'];
		$userinfo['nickname'] = $userinfo['nickName'];	
		
		//$this->returnMsg('ok','登录成功',$backdb);
		$unionid = $data['unionId'];		
		$loginArr = loginUpdate($userinfo,$storeid,$unionid);
		$userid = $loginArr['uid'];
		loginCheckOrder($userid);
		
		$ukey = md5($userid.rand(1, 1000));
		session($userid.'_key', $ukey);		
		session('openid', $openid);	
		session('storeid', $storeid);
		
		$this->returnMsg('ok','登录成功',['uid'=>$userid,'ukey'=>$ukey,'nickName'=>$loginArr['nickName']]);
	}
	
	//小程序获得openid
	public function XcxGetOpenid(){
		
		$code = input('code');	
		$storeid = input('storeid/d',0);		
		$storeinfo  = Db::name('store')->where(['store_id'=>$storeid])->select();
		if(count($storeinfo)<=0){
			$this->returnMsg('-1','获取店铺信息失败');
		}
		
		$secret = $storeinfo[0]['appsecret'];
		$appid = $storeinfo[0]['appid'];
		
		$GetOpenidUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$backdb = vget($GetOpenidUrl);
		
		if(!isset($backdb['openid'])){
			$this->returnMsg('-1','获取微信openid失败',['arr'=>$backdb]);
		}
		
		
		
		$openid = $backdb['openid'];
		$userinfo = input('userInfo/a');		
		$userinfo['openid'] = $openid;
		$userinfo['headimgurl'] = $userinfo['avatarUrl'];
		$userinfo['nickname'] = $userinfo['nickName'];		
		
		//$this->returnMsg('ok','登录成功',$backdb);
		$unionid = $backdb['unionid'];		
		$loginArr = loginUpdate($userinfo,$storeid,$unionid);
		$userid = $loginArr['uid'];
		loginCheckOrder($userid);
		
		$ukey = md5($userid.rand(1, 1000));
		session($userid.'_key', $ukey);		
		session('openid', $openid);	
		session('storeid', $storeid);
		session('logintp', 'xcx');
		
		$this->returnMsg('ok','登录成功',['uid'=>$userid,'ukey'=>$ukey,'nickName'=>$loginArr['nickName']]);
	}
	
	public function LoginTest(){
		session('storeid', 1);
		$this->returnMsg('ok','登录成功');
	}
	
	//用户登录历史
	public function LoginHistory(){
		$code = input('code');	
		$secret = config('AppSecret');//$storeinfo[0]['appsecret'];
		$appid = config('AppId');//$storeinfo[0]['appid'];
		
		$GetOpenidUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
		$backdb = vget($GetOpenidUrl);
		
		if(!isset($backdb['openid'])){
			$this->returnMsg('-1','获取微信openid失败',['arr'=>$backdb]);
		}

		$unionid = $backdb['unionid'];
		$res = Db::query("select * from ml_store where store_id in (select storeid from ml_userlogin where unionid = '$unionid' group by storeid order by id desc)");
		
		if(count($res)<=0){
			$res = Db::query("select * from ml_store where store_id = 1");
		}
		
		$this->returnMsg('ok',$unionid,$res);
	}
	
	//登陆
	public function Login(){
		WxH5Login();
	}
	
	//获取用户信息
	public function getuserinfo(){
		
		$rooturl = config('ROOTURL');
		$appid = config('WxAppId');
		$secret = config('WxAppSecret');
		$code = input('code');
		$storeid = input('storeid');
		$tourl = input('tourl/s','');
		
		if(!$this->isCanUseFun($storeid)){
			$urls = $rooturl.'login.html?&type=timeout';
			header("Location:".$urls);	
			exit();
		}
		
		$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
		$oauth2 = vget($oauth2Url);
		
		if(!isset($oauth2["refresh_token"])){
			$this->returnMsg('-1','token 失效');
		}		

		
		//第二刷新access_token
		$refresh_token = $oauth2["refresh_token"];
		$refauthurl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$refoauth2 = vget($refauthurl);
		
		//第三步:根据全局access_token和openid查询用户信息
		$access_token = $refoauth2["access_token"];
		if(!isset($refoauth2["openid"])){
			$this->returnMsg('-1','获取openid 失败');
		}
		
		//获取用户信息
		$openid = $refoauth2['openid'];		
		$userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$get_user_info_url = $userurl;
		$userinfo = vget($get_user_info_url);
		
		if(!isset($userinfo["openid"])){
			$this->returnMsg('-1','获取 userinfo 失败');
		}
		
		/*$alltokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
		$alltoken = vget($alltokenurl);
		if(!isset($alltoken["access_token"])){
			$this->returnMsg('-1','全局 alltoken 失败');
		}		
		$access_token = $alltoken['access_token'];
				
		$userurl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
		$get_user_info_url = $userurl;
		$unionidinfo = vget($get_user_info_url);*/
		
		//exit(json_encode($userinfo));
		$unionid = $userinfo['unionid'];
		$loginArr = loginUpdate($userinfo,$storeid,$unionid,$openid);
		$userid = $loginArr['uid'];
		loginCheckOrder($userid);
		
		session('openid', $openid);	
		session('storeid', $storeid);
		session('logintp', 'h5');
		
		$sinfo = get_store_info($storeid);
		if(empty($sinfo)){
			$this->returnMsg('-1','店铺信息获取失败');
		}
		
		//$objstr = json_encode(['sname'=>$sinfo['name'],'icon'=>$sinfo['icon']],JSON_UNESCAPED_UNICODE);
		//$urls = $rooturl.'login.html?userid='.$userid.'&storeid='.$storeid.'&type=back&sinfo='.$objstr.'&name='.$sinfo['name'];
		//$urls = $rooturl.'login.html?userid='.$userid.'&storeid='.$storeid.'&type=back&name='.urlencode($sinfo['name']).'&icon='.urlencode($sinfo['icon']);
		//echo"<script>window.location.replace('".$urls."');</script>";
		$urls = $rooturl.'login.html?userid='.$userid.'&storeid='.$storeid.'&type=back';
		header("Location:".$urls);
		
		exit();
	}


		//老板的用户列表
	public function userlist(){
		
		$userid = input('uid/d',0);
		$page = input('page/d',0);
		
		$endPage = config('PageSize');
		$startPage = $page*$endPage;
		
		$result = Db::query("SELECT listid,clientid,username,phone,headimgurl,conndate FROM ml_clientslist,ml_userinfo,ml_userinfo_p 
		WHERE belongto = ? and ml_userinfo.userid = ml_clientslist.clientid and ml_userinfo_p.unionid = ml_userinfo.unionid and 
		ml_userinfo.userid <> ? ORDER BY conndate DESC LIMIT $startPage,$endPage",[$userid,$userid]);
		$this->returnMsg('ok','',$result);
		
	}
	
	
	//收支明细
	public function iaelist(){
		
		$page = input('page/d',0);
		$userid = input('uid/d',0);
		
		
		$result = Db::query("SELECT role,storeid from ml_userinfo where userid = $userid");
		if(count($result)<=0){
			$this->returnMsg('-1','用户不存在');	
		}
		$storeid = $result[0]['storeid'];
		
		$endPage = config('PageSize');
		$startPage = $page*$endPage;
		
		$useGroup = Db::query("select * from ml_userconsume where userid = $userid order by ids desc LIMIT $startPage,$endPage");
		$storeinfo = Db::name('store')->where(['store_id'=>$storeid])->find();
		$storename = $storeinfo['name'];
		
		foreach($useGroup as $key=>$value){
			$useGroup[$key]['storename'] = $storename;
		}			
		
		$this->returnMsg('ok','',$useGroup);
	}
}
